import base64
import json
import pickle

from django import http

from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from utils.response_code import RETCODE


class CartsView(View):
    # 加入购物车
    def post(self,request):

        data=json.loads(request.body.decode())

        # 2.验证数据
        sku_id=data.get('sku_id')
        count=data.get('count')
        selected=data.get('selected',True)

        # 2.1 商品id,个数必须传递
        if not all([sku_id,count]):
            return http.JsonResponse({'code':RETCODE.PARAMERR,'errmsg':'参数不全'})
        # 2.2 判断商品是否存在
        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '没有此商品'})
        # 2.3 判断商品的个数是否为整形
        try:
            count = int(count)
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数错误'})
        # 2.4 判断选中状态是否为bool值
        if not isinstance(selected, bool):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数错误'})
        # 3.判断用户登陆状态
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')

            # redis_conn.hset('carts_%s'%user.id,sku_id,count,)
            redis_conn.hincrby('carts_%s'%user.id,sku_id,count)
            redis_conn.sadd('selected_%s'%user.id,sku_id)
            return http.JsonResponse({'code': RETCODE.OK,'errmsg': 'ok'})
        else:
            carts=request.COOKIES.get('carts')
            if carts is not None:
                decode = base64.b64decode(carts)
                cookie_cart=pickle.loads(decode)
            else:
                # 如果不存在,则初始化字典
                cookie_cart = {}
            if sku_id in cookie_cart:
                original_count=cookie_cart[sku_id]['count']
                count += original_count

            cookie_cart[sku_id] = {
                'count': count,
                'selected': selected
            }
            #     5.2 加密
            # 5.2.1 将字典转换为 bytes类型
            dumps = pickle.dumps(cookie_cart)
            # 5.2.2 将bytes类型进行base64加密
            cookie_data = base64.b64encode(dumps)
            #     5.3 设置cookie
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
            response.set_cookie('carts',cookie_data.decode(),max_age=3600)
            return response

    # 展示
    def get(self,request):
        # 1.判断用户是否登陆
        user = request.user
        if user.is_authenticated:
            # 2.登陆用户到redis中获取数据
            #     2.1 连接redis
            redis_conn = get_redis_connection('carts')
            #     2.2 获取数据 hash   carts_userid: {sku_id:count}
            sku_id_count = redis_conn.hgetall('carts_%s' % user.id)
            #                 set     selected: [sku_id,]
            # [1,2,3]
            selected_ids = redis_conn.smembers('selected_%s' % user.id)

            # 因为 redis和cookie的数据格式不一致,我们需要转换数据
            # 将redis转换为cookie的格式
            # carts: {sku_id:{count:xxx,selected:xxx}}
            cookie_cart = {}

            for sku_id, count in sku_id_count.items():

                # 判断我们遍历的商品id,是否在选中的列表中
                if sku_id in selected_ids:
                    selected = True
                else:
                    selected = False

                cookie_cart[int(sku_id)] = {
                    'count': int(count),
                    # 'selected':sku_id in selected_ids
                    'selected': selected
                }

        else:
            # 3.未登录用户到cookie中获取数据
            carts = request.COOKIES.get('carts')
            #     3.1 获取cookie中carts数据,同时进行判断
            if carts is not None:
                # 有数据
                decode = base64.b64decode(carts)
                cookie_cart = pickle.loads(decode)
            else:
                # 没有数据
                cookie_cart = {}
                #    carts: {sku_id:{count:xxx,selected:xxx}}

        # carts: {sku_id:{count:xxx,selected:xxx}}
        # 4 获取所有商品的id
        ids = cookie_cart.keys()
        # 5 根据商品id查询商品的详细信息 [sku,sku,sku]
        # Decimal
        # mysql: float,double,decimal(货比类型)
        skus = []
        for id in ids:
            sku = SKU.objects.get(pk=id)
            # 6 将对象转换为字典
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cookie_cart.get(sku.id).get('count'),
                'selected': str(cookie_cart.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * cookie_cart.get(sku.id).get('count')),
            })
        context = {
            'cart_skus': skus,
        }

        # 渲染购物车页面
        return render(request, 'cart.html', context)

    # 修改 更新
    def put(self, request):
        # 1.接收数据
        data = json.loads(request.body.decode())

        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected', True)

        # 2.1 商品id,个数必须传递
        if not all([sku_id, count, selected]):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数不全'})
        # 2.2 判断商品是否存在
        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '没有此商品'})
        # 2.3 判断商品的个数是否为整形
        try:
            count = int(count)
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数错误'})
        # 2.4 判断选中状态是否为bool值
        if not isinstance(selected, bool):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数错误'})
        # 3.判断用户登陆状态
        user = request.user
        if user.is_authenticated:
            # 4.登陆用户redis
            #     4.1 连接redis
            redis_conn = get_redis_connection('carts')
            #     4.2 更新数据
            # hash
            redis_conn.hset('carts_%s' % user.id, sku_id, count)
            # set
            if selected:
                redis_conn.sadd('selected_%s' % user.id, sku_id)
            else:
                redis_conn.srem('selected_%s' % user.id, sku_id)
            # 4.3 返回相应
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_sku': cart_sku})

        else:
            # 5.未登录用户cookie
            #     5.1 获取cookie中的carts数据
            carts = request.COOKIES.get('carts')
            #     5.2 判断数据是否存在
            if carts is not None:
                # 存在,解密
                cookie_cart = pickle.loads(base64.b64decode(carts))
            else:
                # 不存在
                cookie_cart = {}
            # 5.3 更新数据
            # {sku_id:{count:xxx,selected:xxxx}}
            if sku_id in cookie_cart:
                cookie_cart[sku_id] = {
                    'count': count,
                    'selected': selected
                }
                #     5.4 对新数据进行加密处理
                cookie_data = base64.b64encode(pickle.dumps(cookie_cart))
            # 5.5 返回相应
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_sku': cart_sku})

            response.set_cookie('carts', cookie_data.decode(), 3600)

            return response

    def delete(self, request):
        # 1.接收数据(sku_id)
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        # 2.验证数据(验证商品是否存在)
        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '无此数据'})
        # 3.获取用户信息
        user = request.user
        if user.is_authenticated:
            # 4.登陆用户操作redis
            #     4.1 连接redis
            redis_conn = get_redis_connection('carts')
            #     4.2 删除数据 hash,set
            # hash
            redis_conn.hdel('carts_%s' % user.id, sku_id)
            # set
            redis_conn.srem('selected_%s' % user.id, sku_id)
            #     4.3 返回相应
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

        else:
            # 5.未登录用户操作cookie
            #     5.1 获取carts数据
            carts = request.COOKIES.get('carts')
            #     5.2 判断数据是否存在
            if carts is not None:
                # 有数据
                cookie_cart = pickle.loads(base64.b64decode(carts))
            else:
                # 没有数据
                cookie_cart = {}
            # 5.3 删除数据
            if sku_id in cookie_cart:
                del cookie_cart[sku_id]
            # 5.4 对最新的数据进行加密处理
            cookie_data = base64.b64encode(pickle.dumps(cookie_cart))
            #     5.5 返回相应
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

            response.set_cookie('carts', cookie_data, 3600)

            return response